package com.wy2cloud.authorize.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.springframework.util.StringUtils;

public class ProxyPrefixHttpServletRequestWrapper extends HttpServletRequestWrapper {

	private static final String Default_Context_Path="/";
	
	private final Boolean amendServletPath;
	
	public ProxyPrefixHttpServletRequestWrapper(HttpServletRequest request) {
		super(request);
		amendServletPath=false;
	}
	
	

	public ProxyPrefixHttpServletRequestWrapper(HttpServletRequest request, Boolean amendServletPath) {
		super(request);
		this.amendServletPath = amendServletPath;
	}



	private HttpServletRequest _getHttpServletRequest() {
        return (HttpServletRequest) super.getRequest();
    }
	

	
	@Override
	public String getContextPath() {
		String contextPath=_getHttpServletRequest().getContextPath();

        //取zuul下发的proxy-header信息
        String prefixPath= HttpServletUtils.getZuulPrefix(_getHttpServletRequest(),false);
        if(prefixPath == null){
            prefixPath="";

        }
        if(!Default_Context_Path.equals(contextPath)){
        	contextPath=prefixPath+contextPath;
        }else {
        	contextPath=prefixPath;
        }
        return contextPath;
	}
	
	@Override
	public String getServletPath() {
		String servletPath=_getHttpServletRequest().getServletPath();
		if(!amendServletPath) {
			return servletPath;
		}
		String prefixPath= HttpServletUtils.getZuulPrefix(_getHttpServletRequest(),true);
        if(prefixPath == null){
            prefixPath="";
        }
        if(!Default_Context_Path.equals(servletPath)){
        	servletPath=prefixPath+servletPath;
        }else {
        	servletPath=prefixPath;
        }
        return servletPath;
	}
}
